﻿using SvgTool.Client.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace SvgTool.Client.ViewModels
{
    public class MainWindowViewModel: NotifyBase
    {
        private List<SvgItem> svgItems;

        public List<SvgItem> SvgItems
        {
            get { return svgItems; }
            set { svgItems = value; OnPropertyChanged(); }
        }

        private string savePath;

        public string SavePath
        {
            get { return savePath; }
            set { savePath = value; OnPropertyChanged(); }
        }

        private string operationMsg;

        public string OperationMsg
        {
            get { return operationMsg; }
            set { operationMsg = value;OnPropertyChanged(); }
        }

        private string msgColor;

        public string MsgColor
        {
            get { return msgColor; }
            set { msgColor = value; OnPropertyChanged(); }
        }

        /// <summary>
        /// 当前listbox选择的svg项
        /// </summary>
        private SvgItem selectedItem;

        public SvgItem SelectedItem
        {
            get { return selectedItem; }
            set { selectedItem = value;OnPropertyChanged(); }
        }



        public DelegateCommand<FrameworkElement> SaveImageCommand { get; set; }
        public DelegateCommand<string> ButtonClickCommand { get; set; }
        
        public MainWindowViewModel() {
            initCommand();
            SavePath = "";
        }

        private void initCommand()
        {
            SaveImageCommand = new DelegateCommand<FrameworkElement>(saveToImage);
            ButtonClickCommand = new DelegateCommand<string>(buttonClick);
        }

        private void saveToImage(FrameworkElement frameworkElement)
        {
            if (!Regex.IsMatch(savePath, "^([a-z]|[A-Z]:\\\\){1}.*$"))
            {
                changeMsg("保存路径错误！", "red");
                return;
            }
            else
            {
                if (!Directory.Exists(savePath))
                {
                    try
                    {
                        var info = Directory.CreateDirectory(savePath);
                    }
                    catch (Exception)
                    {
                        changeMsg("保存路径错误！", "red");
                        return;
                    }
                }
            }

            var displayname = SelectedItem?.DisplayName;
            string fileName = string.IsNullOrEmpty(displayname)
                ? Guid.NewGuid().ToString("N").Substring(0,8) : displayname.Substring(0,displayname.LastIndexOf("."));

            string filePath = Path.Combine(savePath,fileName + ".jpg");

            // 创建RenderTargetBitmap对象
            RenderTargetBitmap bmp = new RenderTargetBitmap((int)frameworkElement.ActualWidth, (int)frameworkElement.ActualHeight, 96d, 96d, PixelFormats.Pbgra32);
            // 调用Render方法渲染控件内容
            bmp.Render(frameworkElement);
            // 创建BitmapEncoder对象，用于保存图片
            BitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bmp));
            // 保存图片到指定路径
            using (FileStream fs = new FileStream(filePath, FileMode.Create))
            {
                encoder.Save(fs);
            }

            changeMsg($"保存成功，路径：{filePath}","green");
        }

        private void changeMsg(string msg,string color="black")
        {
            MsgColor = color;
            OperationMsg = msg;
        }

        private void buttonClick(string param)
        {
            switch(param)
            {
                case "btn_Open":
                    openSvgFiles();
                    return;
                case "btn_Clear":
                    SvgItems = new List<SvgItem>();
                    return;
                case "btn_selectSavePath":
                    selectSavePath();
                    return;

            }
        }

        private void openSvgFiles()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "SVG文件(*.svg)|*.svg"; // 设置文件过滤器，这里是所有文件
            openFileDialog.Multiselect = true; // 允许选择多个文件
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string[] selectedFilePaths = openFileDialog.FileNames;
                // 处理选中的文件路径数组
                // 可以在这里读取文件内容、加载文件等操作
                var listFiles = new List<SvgItem>();
                foreach (string file in selectedFilePaths)
                {
                    string displayName = file.Split('\\').Last();
                    listFiles.Add(new SvgItem() { FilePath = file, UriFile = new Uri(file),DisplayName= displayName });
                }

                SvgItems = listFiles;
            }
        }

        private void selectSavePath()
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.RootFolder = Environment.SpecialFolder.MyDocuments;
            if (folderBrowserDialog.ShowDialog()== DialogResult.OK)
            {
                SavePath = folderBrowserDialog.SelectedPath;    //获取选择的文件夹的全路径名
            }        
            
        }
    }

    //public class SvgItem
    //{
    //    public string? FilePath { get; set; }

    //    public Uri? UriFile { get; set; }

    //    public string? DisplayName { get; set; }
    //}
}
